package com.xiao.singleapp.utils;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.sql.*;

/**
 * JDBC 工具类
 * 用于床架连接，以及资源释放
 *
 * @CreateBy 花和尚  1130365579@qq.com  2023/3/19 17:54
 * @Version 1.0
 */
public class JdbcUtil {

    // 读取配置
    private static Configuration config = null;

    static {
        try {
            // 读取配置 加载驱动
            config = new PropertiesConfiguration("jdbc.properties");
            Class.forName(config.getString("driverClass"));
        } catch (ConfigurationException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取数据库连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConn() throws SQLException {
        String url = config.getString("url");
        String username = config.getString("username");
        String password = config.getString("password");

        // 获取连接
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放连接资源
     * 释放顺序为 rs stat conn
     *
     * @param rs   结果集
     * @param stat 执行器
     * @param conn 数据库连接
     * @throws SQLException
     */
    public static void release(ResultSet rs, Statement stat, Connection conn) throws SQLException {
        if (rs != null) {
            rs.close();
        }
        if (stat != null) {
            stat.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
